/*-----------------------------------------------------
 * 权限子系统
 * ---------------------------------------------------*/
jx.auth = {
    /**
     * 定时任务
     * @param fn
     * @param interval
     */
    autoTask: function (fn, interval) {
        var callback = function () {
            fn();
            setTimeout(callback, interval);
        };

        setTimeout(callback, interval);
    },
    /**
     * 提交当前表单
     */
    submitCurrentForm: function (element) {
        $(element).closest('form').find(':submit').click();
    },
    /**
     * 详情对话框
     */
    iconDialog: function (ops) {
        var url = '/icon';
        if (ops.inputId) {
            var inputId = ops.inputId;
            url = jx.setUrlParam(url, 'inputId', inputId)
        }
        var def = {
            title: '选择图标',
            shadeClose: true,
            width: '90%',
            url: jx.apiUrl(url),
            height: '80%'
        };
        if (ops.callback) {
            def.end = function () {
                ops.callback($('#' + ops.inputId).val());
            };
        }
        jx.dialog($.extend({}, def, ops));
    },
    /**
     * 初始化标签页
     */
    tabsInit: function (callback) {
        $('a[data-toggle="tab"]').on('shown.bs.tab', function () {
            var $this = $(this);
            if ($this.data('_init')) return;
            $this.data('_init', 1);
            var id = this.hash.substr(1);
            if (callback) {
                callback(id);
            }
        });
    },
    /**
     * 初始化授权标签页
     */
    tabsAuthInit: function (callback) {
        jx.auth.tabsInit(function (id) {
            if (id == 'tab-history') {
                $('#jx-history-grid').jxgrid();
            }
            else if (id == 'tab-member') {
                $('#jx-member-user-grid').jxgrid();
            }
            else if (id == 'tab-user-member') {
                $('#userMemberDetailsGrid').jxgrid();
            }
            else if (id == 'tab-module') {
                $('#jxAuthModuleDetails').jxtree();
            }
            if (id == 'tab-role') {
                $('#jx-owner-role-grid').jxgrid();
            }
            // else if (id == 'tab-data') {
            //     $('#jxAuthDataDetails').jxtree();
            // }
            else if (callback) {
                callback(id);
            }
        });
    },
    /**
     * 用户表格行双击事件
     * @param index
     * @param row
     */
    onUserGridDblClickRow: function (index, row) {
        var gridInstance = $(this).jxgrid();
        var id = gridInstance.getRowId(row);
        if (!id) return;
        jx.auth.showUserDetails(id);
    },
    /**
     * 角色表格行双击事件
     * @param index
     * @param row
     */
    onRoleGridDblClickRow: function (index, row) {
        var gridInstance = $(this).jxgrid();
        var id = gridInstance.getRowId(row);
        if (!id) return;
        jx.auth.showRoleDetails(id);
    },
    /**
     * 显示角色详情对话框
     * @param id 主键
     */
    showRoleDetails: function (id) {
        if (!id) return;
        jx.detailsDialog({
            title: '查看角色详细信息',
            url: jx.apiUrl('/auth/role/details'),
            params: {id: id},
            anim: -1,
            offset: 'auto',
            width: '700px',
            height: '70%'
        });
    },
    /**
     * 显示用户详情对话框
     * @param id 主键
     */
    showUserDetails: function (id) {
        if (!id) return;
        jx.detailsDialog({
            title: '查看用户详细信息',
            url: jx.apiUrl('/auth/user/details'),
            params: {id: id},
            anim: -1,
            offset: 'auto',
            width: '700px',
            height: '70%'
        });
    },
    /**
     * 显示部门详情对话框
     * @param id 主键
     */
    showDepartmentDetails: function (id) {
        if (!id) return;
        jx.detailsDialog({
            title: '查看组织机构详细信息',
            url: jx.apiUrl('/auth/department/details'),
            params: {id: id},
            anim: -1,
            offset: 'auto',
            width: '700px',
            height: '70%'
        });
    },

    /**
     * 获取简洁版UE编辑器配置
     */
    simpleUEOptions: function () {
        var ops = {
            initialFrameWidth: '100%',
            initialFrameHeight: 200,
            autoHeightEnabled: false,//是否自动长高,默认true
            scaleEnabled: true,//是否可以拉伸长高,默认true(当开启时，自动长高失效)
            enableAutoSave: true,   //启用自动保存
            saveInterval: 2000,     //自动保存间隔时间， 单位ms
            toolbars: [[
                'paragraph', 'fontfamily', 'fontsize', '|',
                'forecolor', 'backcolor', 'bold', 'italic', 'underline', 'fontborder', 'strikethrough', '|',
                'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', 'insertorderedlist', 'insertunorderedlist', '|',
                'rowspacingtop', 'rowspacingbottom', 'lineheight', '|',
                'simpleupload', 'link', '|',// 'pagebreak', 'insertcode', 'insertimage', 'scrawl', 'unlink', '|',
                'removeformat', 'formatmatch', 'autotypeset', 'fullscreen', 'source'//, 'help', 'undo', 'redo'
            ]]
        };
        return ops;
    },
    editData: function (gridInstance, ops) {
        if (!gridInstance.hasSelectedRow()) return;
        var id = gridInstance.getSelectedRowId();
        ops.params = $.extend({}, ops.params, {id: id});
        jx.dialog(ops);
    },
    deleteData: function (gridInstance, ops) {
        if (!gridInstance.hasCheckedRow()) return;
        var ids = gridInstance.getCheckedRowIds();
        ops.data = $.extend({}, ops.data, {ids: ids.join()});
        if (!ops.success) {
            ops.success = function () {
                gridInstance.reloadGridData();
            }
        }
        jx.delete(ops);
    },
    detailsData: function (gridInstance, row, ops) {
        var id = gridInstance.getRowId(row);
        if (!id) return;
        ops.params = $.extend({}, ops.params, {id: id});
        jx.detailsDialog(ops);
    },
    exportData: function (exportUrl, data) {
        jx.export(exportUrl, data);
    },

    gridContextMenuHandle: function (gridInstance, e, index, row) {
        gridInstance.unselectAll();
        gridInstance.selectRow(index);
    },
    showGridContextMenu: function (gridInstance, contextmenuSelector) {
        gridInstance.getDataBodyPanel().contextmenu({target: contextmenuSelector});
    },

    editFormContinuousSave: function ($form) {
        jx.auth.isContinuousSave = true;
        jx.auth.editFormSave($form);
    },
    editFormSave: function ($form) {
        if (!$form) {
            $form = $('#editform');
        }
        $form.jxform().submit();
    },
    editFormCancel: function () {
        jx.closeDialog();
    },
    bindEditFormSuccess: function ($form) {
        if (!$form) {
            $form = $('#editform');
        }
        $form.onFormSuccess(function (e, result) {
            if (jx.auth.isContinuousSave === true) {
                top.jx.toastr.success('保存成功');
                window.location.reload();
            }
            else {
                top.jx.toastr.success('保存成功');
                jx.closeDialog();
                pwin.reloadGridData();
            }
        });
    }
};


/**
 * bool/数字格式化函数
 */
jx.gf.bool = function (v) {
    if ((jx.isNumber(v) && v === 1) || (jx.isBool(v) && v === true)) {
        return '<i class="fa fa-check"></i>';
    }
    return '<i class="fa fa-close"></i>';
};

/**
 * 状态格式化函数
 */
jx.gf.status = function (v, row, index) {
    var id = row.id;
    var cls = v == '1' ? 'fa-toggle-on' : 'fa-toggle-off';
    return jx.formatString('<i class="fa {0} gridstatus" data-id="{1}" data-val="{2}"></i>', cls, id, v);
};

/**
 * 历史记录操作类型列格式化函数
 */
jx.gf.histroyOperateType = function (v, row) {
    if (!v) return v;
    var url = jx.apiUrl('/auth/history/details?id=' + row.id);
    var options = jx.formatString("{title: '历史记录详细信息',url: '{0}',width: '50%',height: '100%',shadeClose:true,offset: 'rt',anim: 2}", url);
    return jx.formatString('<a class="jxdialog" data-options="{0}">{1}</a>', options, row.operateTypeText);
};

//子页面标题全屏组件
jx.complete(function () {
    $(document.body).on('click','.jxfs',function () {
        top.app.toggleFullPage();
        var $this = $(this);
        var isfs = localStorage.getItem('appPageFull');
        if (isfs === 'true') {
            $this.addClass('jxfs-actual');
        }
        else {
            $this.removeClass('jxfs-actual');
        }
    });
});